<script lang="ts">
//使用<keep-alive></keep-alive>缓存路由必须显式的声明name
export default {
  name: "stoneinfo",
};
</script>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  get_stoneinfo,
  get_stoneinfotable,
  inssert_stoneinfotable,
  update_stoneinfotable,
  delete_stoneinfotable,
} from "../../request/api";
import { ElMessage } from "element-plus";
import type { ElForm } from "element-plus";
import type { ElTable } from "element-plus";
import {
  Plus,
  Refresh,
  RefreshRight,
  Setting,
  EditPen,
  Delete,
} from "@element-plus/icons-vue";
//宝石信息分类的表格
const stoneinfoname = ref([]);
//宝石信息点中的表格信息
const stoneinfotable = ref([]);
//表头
const stoneinfoheader = ref([]);
//当前进入的主表
const currenttable = ref();
//loding
const loading = ref(false);
//弹出框类型0是新增1是修改
const dialogtype = ref(0);
//弹出框
const dialogVisible = ref(false);
//点击名称时获取所有分类
const StoneCategory = ref([]);

//当前列的id名称和id值
const id = reactive({
  name: "",
  value: 0,
});

//分页
const total = ref(); //总条数
const currentPage = ref(1); //当前页数
const pageSize = ref(10); //每页显示条目个数

//宝石分类表单
const StoneCategoryform = reactive({
  StoneCategory_name: "",
  StoneCategory_remark: "",
  StoneCategory_weightunit: "",
  StoneCategory_category: "",
});
//宝石净度表单
const StoneClarityform = reactive({
  StoneClarity_name: "",
  StoneClarity_remark: "",
});
//宝石颜色表单
const StoneColorform = reactive({
  StoneColor_name: "",
  StoneColor_remark: "",
});
//宝石切工表单
const StoneCutform = reactive({
  StoneCut_name: "",
  StoneCut_remark: "",
});
//宝石镶嵌表单
const StoneInlayform = reactive({
  StoneInlay_name: "",
  StoneInlay_remark: "",
});
//宝石名称表单
const StoneNameform = reactive({
  StoneName_name: "",
  StoneName_StoneCategory_id: "",
  StoneName_remark: "",
});
//宝石形状表单
const StoneShapeform = reactive({
  StoneShape_name: "",
  StoneShape_remark: "",
});
//表单规则
const rules = reactive({
  StoneCategory_name: [
    {
      required: true,
      message: "宝石种类不能为空",
      trigger: "blur",
    },
  ],
  StoneCategory_weightunit: [{
    required: true,
    message: "重量单位不能为空",
    trigger: "blur",

  }],
  StoneCategory_category: [{
    required: true,
    message: "大类不能为空",
    trigger: "blur",

  }],
  StoneClarity_name: [
    {
      required: true,
      message: "宝石净度不能为空",
      trigger: "blur",
    },
  ],
  StoneColor_name: [
    {
      required: true,
      message: "宝石颜色不能为空",
      trigger: "blur",
    },
  ],
  StoneCut_name: [
    {
      required: true,
      message: "宝石切工不能为空",
      trigger: "blur",
    },
  ],
  StoneInlay_name: [
    {
      required: true,
      message: "镶嵌名称不能为空",
      trigger: "blur",
    },
  ],
  StoneName_name: [
    {
      required: true,
      message: "宝石名称不能为空",
      trigger: "blur",
    },
  ],
  StoneShape_name: [
    {
      required: true,
      message: "形状名称不能为空",
      trigger: "blur",
    },
  ],
  StoneName_StoneCategory_id: [
    {
      required: true,
      message: "分类不能为空",
      trigger: "blur",
    },
  ],
});

type FormInstance = InstanceType<typeof ElForm>;
const formRef = ref<FormInstance>();

//设置一进入页面就点击第一页
const stoneinfotableref = ref<InstanceType<typeof ElTable>>();

//刷新数据
const RefreshTbale = async (currenttable, currentPage, pagsize) => {
  loading.value = true;
  const { data } = await get_stoneinfotable(currenttable, currentPage, pagsize);
  loading.value = false;
  if (data.code == 200) {
    stoneinfoheader.value = data.header;
    stoneinfotable.value = data.data.data;

    total.value = data.data.total; //总条数

    // formfalg.value = val.table; //新增表单页的显示

    console.log(stoneinfoheader.value);
  } else {
    ElMessage.error(data.msg);
  }
};

//进入页面请求宝石信息分类名称
const { data } = await get_stoneinfo();
if (data.code == 200) {
  stoneinfoname.value = data.data;
} else {
  ElMessage.error(data.msg);
}

//监听已
onMounted(() => {
  //设置一进入就默认第一项
  stoneinfotableref.value!.setCurrentRow(stoneinfoname.value[0]);
});

//点击宝石信息表格的方法
const handchangestoneinfo = async (val) => {
  loading.value = true;
  const { data } = await get_stoneinfotable(val.table, currentPage.value, pageSize.value);
  loading.value = false;
  currenttable.value = val.table;

  if (data.code == 200) {
    stoneinfoheader.value = data.header;
    stoneinfotable.value = data.data.data;
    if (val.table == "SET_StoneName") {
      StoneCategory.value = data.data.StoneCategory;
    }

    total.value = data.data.total; //总条数

    // formfalg.value = val.table; //新增表单页的显示

    console.log(stoneinfoheader.value);
  } else {
    ElMessage.error(data.msg);
  }
};

//点击添加按钮
const tianjia = () => {
  dialogtype.value = 0;
  dialogVisible.value = true;
  // console.log(dialogVisible.value)
};

//点击修改按钮
const updateclick = (row) => {
  dialogtype.value = 1;
  dialogVisible.value = true;
  //表单绑定的数据项
  // let formname = formfalg.value.substr(4) + "form";
  let formname = currenttable.value.substr(currenttable.value.indexOf("_") + 1) + "form";
  //存储id的字段名和id的值
  let idname = currenttable.value.substr(currenttable.value.indexOf("_") + 1) + "_id";
  id.name = idname;
  id.value = row[idname];
  // console.log(id);

  //clearform();
  nextTick(() => {
    Object.keys(eval(formname)).map((key) => {
      console.log(key);
      Object.keys(row).map((key2) => {
        if (key == key2) {
          eval(formname)[key] = row[key2];
        }
      });
    });
  });

  console.log(row);
  console.log(eval(formname));
};

//点击删除按钮
const delclick = async (row) => {
  //id字段
  let idname = currenttable.value.substr(currenttable.value.indexOf("_") + 1) + "_id";
  const { data } = await delete_stoneinfotable(row[idname], currenttable.value);
  if (data.code == 200) {
    ElMessage.success("删除成功");

    RefreshTbale(currenttable.value, currentPage.value, pageSize.value);
  } else {
    ElMessage.error(data.msg);
  }
};
//点击刷新按钮
const refreshclick = () => {
  RefreshTbale(currenttable.value, currentPage.value, pageSize.value);
  ElMessage.success("刷新成功");
};

//点击开关按钮
//coumname为当前列的字段名,idname为id的名字,val为值
const switchcilik = async (val, coumname, row) => {
  // console.log(val);
  // console.log(goodsinfotable.value);
  let idname = coumname.substr(0, coumname.indexOf("_")) + "_id";
  //要更新的列的id名称和值
  let id = {
    name: idname,
    value: row[idname],
  };
  //要更新的键值对
  let updatedata = {};
  updatedata[coumname] = val;
  //更新商品信息
  const { data } = await update_stoneinfotable(id, currenttable.value, updatedata);
  if (data.code == 200) {
    ElMessage.success("更新成功");
  } else {
    // loadingswitch.value = true;

    ElMessage.error(data.msg);
    RefreshTbale(currenttable.value, currentPage.value, pageSize.value);
    // console.log(val);
  }
  // console.log(updatedata);
};

//监听current-page事件
const handleCurrentChange = async (newpage) => {
  RefreshTbale(currenttable.value, newpage, pageSize.value);
};
//监听page-size每页条数
const handleSizeChange = async (pagesize) => {
  RefreshTbale(currenttable.value, currentPage.value, pagesize);
};

//关闭模态框之前清空表单数据
const beforeclosedialog = (done) => {
  //清空表单数据
  formRef.value!.resetFields();
  return done(false);
};
//点击模态框取消按钮
const cancel = (formEl: FormInstance | undefined) => {
  //clearform();
  formRef.value!.resetFields();
  dialogVisible.value = false;
};

//点击表单确认按钮
const dianlogclick = (currenttable, formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      console.log("验证通过");
      let formname = currenttable.substr(currenttable.indexOf("_") + 1) + "form";
      let foremdata = eval(formname);
      if (dialogtype.value == 0) {
        //插入新数据
        const { data } = await inssert_stoneinfotable(currenttable, foremdata);
        if (data.code == 200) {
          ElMessage.success("新增成功");

          formEl.resetFields();
          dialogVisible.value = false;
          //重新请求数据
          RefreshTbale(currenttable, currentPage.value, pageSize.value);
        } else {
          ElMessage.error(data.msg);
        }
      } else if (dialogtype.value == 1) {
        // console.log(currenttable.va);
        const { data } = await update_stoneinfotable(id, currenttable, foremdata);

        if (data.code == 200) {
          dialogVisible.value = false;
          formEl.resetFields();
          ElMessage.success("修改成功");

          //重新请求数据
          RefreshTbale(currenttable, currentPage.value, pageSize.value);
        } else {
          ElMessage.error(data.msg);
        }
      }
    } else {
      console.log("验证未通过");
    }
  });
};
</script>

<template>
  <div class="el-card_body">
    <el-row :gutter="20">
      <el-col :span="24" :lg="6">
        <el-table ref="stoneinfotableref" class="left_table" :data="stoneinfoname" border highlight-current-row
          style="width: 100%" :header-cell-style="{ background: '#f6f8f9', color: '#000000' }"
          height="calc(100vh - 261px)" max-height="calc(100vh - 261px)" @current-change="handchangestoneinfo">
          <el-table-column align="center" type="index" width="50" />
          <el-table-column prop="name" label="宝石信息" />
        </el-table>
      </el-col>
      <el-col :span="24" :lg="18">
        <el-table v-loading="loading" :data="stoneinfotable" border style="width: 100%" height="calc(100vh - 261px)"
          max-height="calc(100vh - 261px)" :header-cell-style="{ background: '#f6f8f9', color: '#000000' }">
          <el-table-column label="Address Info">
            <template #header>
              <div class="ele-table-tool ele-table-tool-default">
                <el-button type="primary" :icon="Plus" @click="tianjia">添加</el-button>
                <div class="ele-tool">
                  <el-tooltip effect="dark" content="刷新" placement="top">
                    <el-button size="small" :icon="Refresh" @click="refreshclick"></el-button>
                  </el-tooltip>

                  <el-tooltip effect="dark" content="列设置" placement="top">
                    <el-button size="small" :icon="Setting"></el-button>
                  </el-tooltip>
                </div>
              </div>
            </template>
            <el-table-column align="center" type="index" width="50" />
            <template v-for="(item, index) in stoneinfoheader" :key="index">
              <el-table-column resizable :prop="item.prop" :label="item.lable" align="center" v-if="!item.switch"
                min-width="100" />
              <el-table-column :prop="item.prop" :label="item.lable" v-if="item.switch" align="center" width="80">
                <template #default="scope">
                  <el-switch v-model="scope.row[item.prop]" :active-value="1" :inactive-value="0"
                    @change="switchcilik(scope.row[item.prop], item.prop, scope.row)" />
                </template>
              </el-table-column>
            </template>
            <el-table-column fixed="right" align="center" label="操作" width="140">
              <template #default="scope">
                <el-button type="text" :icon="EditPen" @click="updateclick(scope.row)">修改</el-button>
                <el-popconfirm @confirm="delclick(scope.row)" title="是否确认删除?">
                  <template #reference>
                    <el-button class="operate" type="text" :icon="Delete">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <div class="ele-pagination">
          <el-pagination v-model:currentPage="currentPage" background :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @update:current-page="handleCurrentChange"
            @update:page-size="handleSizeChange"></el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
  <!-- 表单的弹出框 -->
  <el-dialog :before-close="beforeclosedialog" v-model="dialogVisible" width="25%"
    :title="dialogtype == 0 ? '添加' : '修改'">
    <!-- 宝石分类 -->
    <el-form ref="formRef" :model="StoneCategoryform" label-width="90px" v-if="currenttable == 'SET_StoneCategory'"
      :rules="rules">
      <el-form-item label="分类名称:" prop="StoneCategory_name">
        <el-input v-model="StoneCategoryform.StoneCategory_name"></el-input>
      </el-form-item>
      <el-form-item label="大类:" prop="StoneCategory_category">
        <el-select v-model="StoneCategoryform.StoneCategory_category" placeholder="请选择">
          <el-option key="1" label="钻石" value="1" />
          <el-option key="2" label="彩宝" value="2" />
          <el-option key="3" label="玉石" value="3" />
          <el-option key="4" label="其他宝石" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="重量单位:" prop="StoneCategory_weightunit">
        <el-select v-model="StoneCategoryform.StoneCategory_weightunit" placeholder="请选择">
          <el-option key="1" label="g" value="1" />
          <el-option key="2" label="ct" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注:" prop="StoneCategory_remark">
        <el-input type="textarea" v-model="StoneCategoryform.StoneCategory_remark"></el-input>
      </el-form-item>

    </el-form>

    <!--宝石净度 -->
    <el-form ref="formRef" :model="StoneClarityform" label-width="90px" v-if="currenttable == 'SET_StoneClarity'"
      :rules="rules">
      <el-form-item label="净度名称:" prop="StoneClarity_name">
        <el-input v-model="StoneClarityform.StoneClarity_name"></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="StoneClarity_remark">
        <el-input type="textarea" v-model="StoneClarityform.StoneClarity_remark"></el-input>
      </el-form-item>
    </el-form>
    <!-- 宝石颜色-->

    <el-form ref="formRef" :model="StoneColorform" label-width="100px" v-if="currenttable == 'SET_StoneColor'"
      :rules="rules">
      <el-form-item label="颜色名称:" prop="StoneColor_name">
        <el-input v-model="StoneColorform.StoneColor_name"></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="StoneColor_remark">
        <el-input type="textarea" v-model="StoneColorform.StoneColor_remark"></el-input>
      </el-form-item>
    </el-form>

    <!-- 宝石切工 -->

    <el-form ref="formRef" :model="StoneCutform" label-width="100px" v-if="currenttable == 'SET_StoneCut'"
      :rules="rules">
      <el-form-item label="切工名称:" prop="StoneCut_name">
        <el-input v-model="StoneCutform.StoneCut_name"></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="StoneCut_remark">
        <el-input type="textarea" v-model="StoneCutform.StoneCut_remark"></el-input>
      </el-form-item>
    </el-form>

    <!-- 宝石镶嵌 -->

    <el-form ref="formRef" :model="StoneInlayform" label-width="100px" v-if="currenttable == 'SET_StoneInlay'"
      :rules="rules">
      <el-form-item label="镶法名称:" prop="StoneInlay_name">
        <el-input v-model="StoneInlayform.StoneInlay_name"></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="StoneInlay_remark">
        <el-input type="textarea" v-model="StoneInlayform.StoneInlay_remark"></el-input>
      </el-form-item>
    </el-form>

    <!-- 宝石名称 -->
    <el-form ref="formRef" :model="StoneNameform" label-width="100px" v-if="currenttable == 'SET_StoneName'"
      :rules="rules">
      <el-form-item label="分类:" prop="StoneName_StoneCategory_id">
        <el-select v-model="StoneNameform.StoneName_StoneCategory_id" placeholder="请选择">
          <el-option v-for="item in StoneCategory" :key="item.StoneCategory_id" :label="item.StoneCategory_name"
            :value="item.StoneCategory_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称:" prop="StoneName_name">
        <el-input v-model="StoneNameform.StoneName_name"></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="StoneName_remark">
        <el-input type="textarea" v-model="StoneNameform.StoneName_remark"></el-input>
      </el-form-item>
    </el-form>

    <!-- 宝石形状 -->

    <el-form ref="formRef" :model="StoneShapeform" label-width="100px" v-if="currenttable == 'SET_StoneShape'"
      :rules="rules">
      <el-form-item label="形状名称:" prop="StoneShape_name">
        <el-input v-model="StoneShapeform.StoneShape_name"></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="StoneShape_remark">
        <el-input type="textarea" v-model="StoneShapeform.StoneShape_remark"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(formRef)">取消</el-button>
        <el-button type="primary" @click="dianlogclick(currenttable, formRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
//左侧表格的样式
/deep/ .left_table {
  height: calc(100vh-261px);
}

//左侧表格下的每一行样式
/deep/ .left_table .el-table__row {
  cursor: pointer;
}

/deep/ .left_table .el-table__row>td:last-child::after {
  content: url(../../assets/arrow-right.png);

  line-height: 1;
  position: absolute;
  right: 10px;
  top: 50%;
  margin-top: -7px;
}

.el-card_body {
  background-color: white;
  padding: 15px;
}

//右侧表头右上角图标
.ele-tool {
  margin: 5px 0 5px auto;
}

.ele-tool .el-button--small {
  padding: 7px 7px;
  font-size: 15px;
  background-color: #f6f8f9;
}

.ele-table-tool {
  display: inline-flex;
  flex-wrap: wrap;
  width: 100%;
}

//分页
.ele-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

/deep/ .operate {
  color: red;
}
</style>
